/*
 * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. This software is open source. See
 * the bottom of this file for the licence.
 */

package org.dom4j.io;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Branch;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.tree.NamespaceStack;

/**
 * <p>
 * <code>DOMReader</code> navigates a W3C DOM tree and creates a DOM4J tree from it.
 * </p>
 * 
 * @author <a href="mailto:jstrachan@apache.org">James Strachan </a>
 * @version $Revision: 1.2 $
 */
public class DOMReader
{
    /** <code>DocumentFactory</code> used to create new document objects */
    private DocumentFactory factory;

    /** stack of <code>Namespace</code> and <code>QName</code> objects */
    private NamespaceStack namespaceStack;

    public DOMReader()
    {
        this.factory = DocumentFactory.getInstance();
        this.namespaceStack = new NamespaceStack(factory);
    }

    public DOMReader(DocumentFactory factory)
    {
        this.factory = factory;
        this.namespaceStack = new NamespaceStack(factory);
    }

    /**
     * DOCUMENT ME!
     * 
     * @return the <code>DocumentFactory</code> used to create document objects
     */
    public DocumentFactory getDocumentFactory()
    {
        return factory;
    }

    /**
     * <p>
     * This sets the <code>DocumentFactory</code> used to create new documents. This method allows
     * the building of custom DOM4J tree objects to be implemented easily using a custom derivation
     * of {@link DocumentFactory}
     * </p>
     * 
     * @param docFactory
     *            <code>DocumentFactory</code> used to create DOM4J objects
     */
    public void setDocumentFactory(DocumentFactory docFactory)
    {
        this.factory = docFactory;
        this.namespaceStack.setDocumentFactory(factory);
    }

    public Document read(org.w3c.dom.Document domDocument)
    {
        if (domDocument instanceof Document)
        {
            return (Document) domDocument;
        }

        Document document = createDocument();

        clearNamespaceStack();

        org.w3c.dom.NodeList nodeList = domDocument.getChildNodes();

        for (int i = 0, size = nodeList.getLength(); i < size; i++)
        {
            readTree(nodeList.item(i), document);
        }

        return document;
    }
    
    // Implementation methods
    protected void readTree(org.w3c.dom.Node node, Branch current)
    {
        String value = node.getNodeValue(), name = node.getNodeName();

        switch (node.getNodeType())
        {
        case org.w3c.dom.Node.ELEMENT_NODE:
            readElement(node, current);
        return;

        case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
            if (current instanceof Element)
                ((Element) current).addProcessingInstruction(name, value);
            else
                ((Document) current).addProcessingInstruction(name, value);
        return;

        case org.w3c.dom.Node.COMMENT_NODE:
            if (current instanceof Element)
                ((Element) current).addComment(value);
            else
                ((Document) current).addComment(value);
        return;

        case org.w3c.dom.Node.DOCUMENT_TYPE_NODE:
            org.w3c.dom.DocumentType dt = (org.w3c.dom.DocumentType) node;
            ((Document) current).addDocType(dt.getName(), dt.getPublicId(), dt.getSystemId());
        return;

        case org.w3c.dom.Node.TEXT_NODE:
            ((Element) current).addText(value);
        return;

        case org.w3c.dom.Node.CDATA_SECTION_NODE:
            ((Element) current).addCDATA(value);
        return;

        case org.w3c.dom.Node.ENTITY_REFERENCE_NODE:
            if (node.getFirstChild() != null)
                ((Element) current).addEntity(name, node.getFirstChild().getNodeValue());
            else
                ((Element) current).addEntity(name, "");
        return;

        case org.w3c.dom.Node.ENTITY_NODE:
            ((Element) current).addEntity(name, value);
        return;

        default:
            System.out.println("WARNING: Unknown DOM node type: " + node.getNodeType());
        }
    }

    protected void readElement(org.w3c.dom.Node node, Branch current)
    {
        int prevNamespaces = namespaceStack.size();
        String namespaceUri = node.getNamespaceURI();
        org.w3c.dom.NamedNodeMap attrList = node.getAttributes();

        if (attrList != null && namespaceUri == null
                && attrList.getNamedItem("xmlns") != null)
            namespaceUri = attrList.getNamedItem("xmlns").getNodeValue();

        Element elm = current.addElement(namespaceStack.getQName(namespaceUri,
                node.getLocalName(), node.getNodeName()));

        if (attrList != null)
            for (int i = 0; i < attrList.getLength(); i++)
            {
                org.w3c.dom.Node attr = attrList.item(i);

                if (attr.getNodeName().startsWith("xmlns"))
                    elm.add(namespaceStack.addNamespace(getPrefix(attr.getNodeName()),
                            attr.getNodeValue()));
                else
                    elm.addAttribute(namespaceStack.getQName(attr.getNamespaceURI(),
                            attr.getLocalName(), attr.getNodeName()), attr.getNodeValue());
            }
        
        for (int i = 0; i < node.getChildNodes().getLength(); i++)
            readTree(node.getChildNodes().item(i), elm);

        while (namespaceStack.size() > prevNamespaces && namespaceStack.pop() != null);

    }

    protected Namespace getNamespace(String prefix, String uri)
    {
        return getDocumentFactory().createNamespace(prefix, uri);
    }

    protected Document createDocument()
    {
        return getDocumentFactory().createDocument();
    }

    protected void clearNamespaceStack()
    {
        namespaceStack.clear();

        if (!namespaceStack.contains(Namespace.XML_NAMESPACE))
        {
            namespaceStack.push(Namespace.XML_NAMESPACE);
        }
    }

    private String getPrefix(String xmlnsDecl)
    {
        int index = xmlnsDecl.indexOf(':', 5);

        if (index != -1)
        {
            return xmlnsDecl.substring(index + 1);
        }
        else
        {
            return "";
        }
    }
}

/*
 * Redistribution and use of this software and associated documentation ("Software"), with or
 * without modification, are permitted provided that the following conditions are met: 1.
 * Redistributions of source code must retain copyright statements and notices. Redistributions must
 * also contain a copy of this document. 2. Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution. 3. The name "DOM4J" must not be used to
 * endorse or promote products derived from this Software without prior written permission of
 * MetaStuff, Ltd. For written permission, please contact dom4j-info@metastuff.com. 4. Products
 * derived from this Software may not be called "DOM4J" nor may "DOM4J" appear in their names
 * without prior written permission of MetaStuff, Ltd. DOM4J is a registered trademark of MetaStuff,
 * Ltd. 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org THIS SOFTWARE IS
 * PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright 2001-2005
 * (C) MetaStuff, Ltd. All Rights Reserved.
 */
